<template>
  <div class="app-container">
    <div style="width: 800px">
      <el-form ref="form" :rules="rules" :model="form" label-width="120px">
        <el-form-item label="优惠券名称" prop="name">
          <el-input clearable size="small" v-model="form.name" placeholder="请输入优惠券名称" />
        </el-form-item>
        <el-form-item label="优惠券金额" prop="amount">
          <el-input clearable size="small" v-model="form.amount" placeholder="请输入优惠券金额" />
        </el-form-item>
        <el-form-item label="有效期限" prop="time">
          <el-date-picker
            style="width:100%;"
            size="small"
            v-model="form.time"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            align="right"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="应用场景" prop="payBizType" required>
          <el-radio-group @change="payBizTypeChange" v-model="form.payBizType">
            <el-radio :label="1">专栏</el-radio>
            <el-radio :label="2">活动</el-radio>
            <el-radio :label="3">线下课</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="应用场景" prop="objId">
          <span
            v-show="selectName&&form.payBizType == 1"
            style="margin-right:20px"
          >已选择专栏：{{selectName}}</span>
          <span
            v-show="selectName&&form.payBizType == 2"
            style="margin-right:20px"
          >已选择活动：{{selectName}}</span>
          <el-button
            @click="openColumnModal"
            v-if="form.payBizType == 1"
            size="small"
            type="primary"
          >选择专栏</el-button>
          <el-button @click="openActivityModal" v-else size="small" type="primary">选择活动</el-button>
        </el-form-item>
        <el-form-item label="选择用户" prop="userIds">
          <el-checkbox @change="userAllChange" style="margin-right:20px;" v-model="checked">是否应用所有用户</el-checkbox>
          <span v-if="!checked">
            <span v-if="choosedUserList.length" style="margin-right:20px">已选择：{{choosedUserList.length}} 个用户</span>
          </span>
          <el-button @click="openUserModal" :disabled="checked" size="small" type="primary">选择用户</el-button>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" @click="onSubmit('form')">保存</el-button>
          <el-button size="small" @click="onCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-dialog top="10vh" width="1000px" title="选择活动" :visible.sync="activtyModal">
      <div style="display:flex;align-items: center;justify-content: space-between;margin:0 0 10px;">
        <div style="display:flex;align-items: center;">
          <el-form :inline="true" class="demo-form-inline">
            <el-form-item label="选择活动">
              <el-input clearable size="small" v-model="activityName" placeholder="活动名称"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button size="small" type="primary" @click="getActivityList">搜索</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <el-table
        @current-change="handleCurrentChangeSelect"
        highlight-current-row
        row-key="id"
        style="width: 100%"
        height="400"
        ref="multipleTable"
        v-loading="listLoading"
        :data="activityList"
        element-loading-text="Loading"
        border
        fit
        empty-text="暂无数据"
      >
        <el-table-column label="ID" width="150">
          <template slot-scope="scope">{{ scope.row.id }}</template>
        </el-table-column>
        <el-table-column label="活动名称">
          <template slot-scope="scope">{{ scope.row.name }}</template>
        </el-table-column>
        <el-table-column label="活动金额" width="200">
          <template slot-scope="scope">{{ scope.row.fee?scope.row.fee==0?'免费':scope.row.fee:'免费' }}</template>
        </el-table-column>
      </el-table>

      <div style="margin:10px 0 0 0;text-align:right;">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="itemObj.pageNum"
          :page-sizes="[10, 30, 50, 100]"
          :page-size="itemObj.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="itemObj.total"
        ></el-pagination>
      </div>

      <div slot="footer" class="dialog-footer" style="text-align:center;">
        <el-button size="small" type="primary" @click="activtyModal = false">关 闭</el-button>
      </div>
    </el-dialog>

    <el-dialog top="10vh" width="1000px" title="选择专栏" :visible.sync="columnModal">
      <div style="display:flex;align-items: center;justify-content: space-between;margin:0 0 10px;">
        <div style="display:flex;align-items: center;">
          <el-form :inline="true" class="demo-form-inline">
            <el-form-item label="选择活动">
              <el-input clearable size="small" v-model="columnName" placeholder="活动名称"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button size="small" type="primary" @click="getColunmList">搜索</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <el-table
        @current-change="handleCurrentChangeSelect"
        highlight-current-row
        row-key="id"
        style="width: 100%"
        height="400"
        ref="multipleTable"
        v-loading="listLoading"
        :data="columnList"
        element-loading-text="Loading"
        border
        fit
        empty-text="暂无数据"
      >
        <el-table-column label="ID" width="150">
          <template slot-scope="scope">{{ scope.row.id }}</template>
        </el-table-column>
        <el-table-column label="专栏名称">
          <template slot-scope="scope">{{ scope.row.name }}</template>
        </el-table-column>
        <el-table-column label="专栏金额" width="200">
          <template slot-scope="scope">{{ scope.row.fee?scope.row.fee:'免费' }}</template>
        </el-table-column>
      </el-table>

      <div style="margin:10px 0 0 0;text-align:right;">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="itemObj.pageNum"
          :page-sizes="[10, 30, 50, 100]"
          :page-size="itemObj.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="itemObj.total"
        ></el-pagination>
      </div>

      <div slot="footer" class="dialog-footer" style="text-align:center;">
        <el-button size="small" type="primary" @click="columnModal = false">关 闭</el-button>
      </div>
    </el-dialog>

    <el-dialog top="10vh" width="1000px" title="选择用户" :visible.sync="userModal">
      <div style="display:flex;align-items: center;justify-content: space-between;margin:0 0 10px;">
        <div style="display:flex;align-items: center;">
          <el-form :inline="true" class="demo-form-inline">
            <el-form-item label="用户昵称">
              <el-input clearable size="small" v-model="userName" placeholder="请输入用户昵称"></el-input>
            </el-form-item>
            <el-form-item label="用户手机号">
              <el-input clearable size="small" v-model="userMobile" placeholder="请输入用户手机号"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button size="small" type="primary" @click="getUserList">搜索</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <el-table row-key="id" style="width: 100%" height="400" @selection-change="handleSelectionChange" ref="multipleTable" v-loading="listLoading" :data="userList" element-loading-text="Loading" border fit highlight-current-row empty-text="暂无数据">
        <el-table-column

          type="selection"
          reserve-selection
          width="80">
        </el-table-column>
        <el-table-column label="ID" width="150">
          <template slot-scope="scope">
            {{ scope.row.id }}
          </template>
        </el-table-column>
        <el-table-column label="用户昵称" width="100">
          <template slot-scope="scope">
            {{ scope.row.nickname }}
          </template>
        </el-table-column>
        <el-table-column label="头像">
          <template slot-scope="scope">
            <img style="width:40px;height:40px;" :src="scope.row.avatar?scope.row.avatar:'/images/avatar.png'" alt="">
          </template>
        </el-table-column>
        <el-table-column label="手机号" width="120">
          <template slot-scope="scope">
            {{ scope.row.mobile }}
          </template>
        </el-table-column>
        <el-table-column label="会员等级" width="200">
          <template slot-scope="scope">
            {{ scope.row.level==0?'非会员':`${scope.row.level}级` }}
          </template>
        </el-table-column>
        <el-table-column label="用户积分" width="200">
          <template slot-scope="scope">
            <div style="display:flex;align-items:center;">
              <div style="color:#66b1ff;">
                {{ scope.row.score }}
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div style="margin:10px 0 0 0;text-align:right;">
        <el-pagination
          @size-change="handleUserSizeChange"
          @current-change="handleUserCurrentChange"
          :current-page="userObj.pageNum"
          :page-sizes="[10, 30, 50, 100]"
          :page-size="userObj.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="userObj.total">
        </el-pagination>
      </div>

      <div slot="footer" class="dialog-footer" style="text-align:center;">
        <el-button size="small" type="primary" @click="userModal = false">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { saveGoodsApi } from "@/api/repurchase";
import { getActivityListApi } from "@/api/activity";
import { getCourseListApi } from "@/api/column";
import { getUserListApi } from '@/api/user';
import { saveCouponApi } from '@/api/marketing'
export default {
  data() {
    return {
      form: {
        name: "",
        amount: "",
        time: [],
        payBizType: 1,
        objId: "",
        userIds: ""
      },
      rules: {
        name: [
          {
            required: true,
            message: "请输入优惠券名称",
            trigger: "blur"
          }
        ],
        amount: [
          {
            required: true,
            message: "请输入优惠券金额",
            trigger: "blur"
          }
        ],
        time: [
          {
            required: true,
            message: "请选择有效期限",
            trigger: "change"
          }
        ],
        objId: [
          {
            required: true,
            message: "请选择优惠对象",
            trigger: "change"
          }
        ],
        userIds: [
          {
            required: true,
            message: "请选择用户",
            trigger: "change"
          }
        ]
      },
      activtyModal: false,
      columnModal: false,
      itemObj: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      listLoading: false,
      activityList: [],
      columnList: [],
      activityName: "",
      columnName: '',
      selectObj: {},
      selectName: "",
      checked: false,
      userObj: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      userName: '',
      userMobile: '',
      userModal: false,
      userList: [],
      choosedUserList: [],
    };
  },
  mounted() {},
  methods: {
    userAllChange(e) {
      if(e) {
        this.rules.userIds[0].required = false
      } else {
        this.rules.userIds[0].required = true
      }
    },
    openColumnModal() {
      this.itemObj.pageNum = 1;
      this.itemObj.pageSize = 10;
      this.itemObj.total = 0;
      this.columnModal = true
      this.columnList = []
      this.columnName = ''
      this.getColunmList()
    },
    openActivityModal() {
      this.itemObj.pageNum = 1;
      this.itemObj.pageSize = 10;
      this.itemObj.total = 0;
      this.activtyModal = true;
      this.activityList = []
      this.activityName = ''
      this.getActivityList();
    },
    getActivityList() {
      this.listLoading = true;
      getActivityListApi({
        name: this.activityName,
        state: 1,
        pageSize: this.itemObj.pageSize,
        pageNum: this.itemObj.pageNum
      }).then(res => {
        this.listLoading = false;
        this.activityList = res.data.result;
        this.itemObj.total = res.data.total;
        this.activityList.forEach((item,index) => {
          if(item.id == this.selectObj.id) {
            this.setCurrent(item)
          }
        })
      });
    },
    getColunmList() {
      this.listLoading = true;
      getCourseListApi({
        name: this.columnName,
        state: 1,
        pageSize: this.itemObj.pageSize,
        pageNum: this.itemObj.pageNum
      }).then(res => {
        this.listLoading = false;
        this.columnList = res.data.result;
        this.itemObj.total = res.data.total;
        this.columnList.forEach((item,index) => {
          if(item.id == this.selectObj.id) {
            this.setCurrent(item)
          }
        })
      });
    },
    openUserModal() {
      this.userList = []
      this.userObj.pageSize = 10
      this.userObj.pageNum = 1
      this.userObj.total = 0
      this.userName = ''
      this.userMobile = ''
      this.userModal = true
      this.getUserList()
    },
    handleSelectionChange(e) {
      this.choosedUserList = e
      this.form.userIds = e.map(item => item.id).toString()
    },
    getUserList() {
      this.listLoading = true
      getUserListApi({
        nickname: this.userName,
        mobile: this.userMobile,
        pageSize: this.userObj.pageSize,
        pageNum: this.userObj.pageNum
      }).then(res => {
        this.listLoading = false;
        this.userList = res.data.result;
        this.userObj.total = res.data.total;
      });
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.itemObj.pageSize = val;
      if (this.form.payBizType == 1) {
        this.getColunmList();
      } else {
        this.getActivityList();
      }
    },

    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.itemObj.pageNum = val;
      if (this.form.payBizType == 1) {
        this.getColunmList();
      } else {
        this.openActivityModal();
      }
    },
    handleUserSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.userObj.pageSize = val;
      this.getUserList()
    },
    handleUserCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.userObj.pageNum = val;
      this.getUserList()
    },
    setCurrent(row) {
      this.$refs.multipleTable.setCurrentRow(row);
    },
    handleCurrentChangeSelect(e) {
      this.selectObj = e;
      this.selectName = e.name;
      this.form.objId = e.id;
    },
    payBizTypeChange(e) {
      this.form.payBizType = e;
      this.selectObj = {};
      this.selectName = "";
      this.form.objId = "";
    },
    onSubmit(formName) {
      // this.$message('submit!')
      console.log(this.form);
      this.$refs[formName].validate(valid => {
        if (valid) {
          saveCouponApi({
            name: this.form.name,
            amount: this.form.amount,
            objId: this.form.objId,
            payBizType: this.form.payBizType,
            userIds: this.checked?-1:this.form.userIds,
            startTime: this.form.time[0],
            endTime: this.form.time[1]
          }).then(res => {
            this.$message.success("操作成功！");
            setTimeout(() => {
              this.$router.back(-1);
            }, 1000);
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    onCancel() {
      this.$router.back(-1);
    }
  }
};
</script>

<style scoped>
.line {
  text-align: center;
}
</style>
